/**
 * title: 填写企业信息
 */
import React, { Component } from 'react';
import { Form, Input, Row, Col, Icon, DatePicker, Checkbox, Tooltip, message, Select } from 'antd';
import { CitySelect, OssUpload, UploadImageSample } from 'scd';
import { connect } from 'dva';
import Wrapper from './components/Wrapper';
import getFileId from '@/utils/getFileId';
import moment from 'moment';
import Actions from './components/Actions';
const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;

@connect(({ createCompany: { companyInformation }, loading: { models: { createCompany } } }) => ({
  companyInformation,
  loading: !!createCompany,
}))
@Form.create()
class CompanyForm extends Component {
  componentDidMount() {
    const {
      location: {
        query: { temId },
      },
      dispatch,
    } = this.props;
    if (temId) {
      dispatch({
        type: 'createCompany/queryForm',
        payload: {
          temId,
          step: 1,
        },
      }).catch(errMsg => {
        message.error(errMsg);
      });
    }
  }

  handleSubmit = type => e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      history,
      location: {
        query: { temId },
      },
    } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        // console.log('Received values of form: ', fieldsValue);
        let values = {
          ...fieldsValue,

          // 注册地址省市区
          provinceId: fieldsValue.companyRegisterCity[0],
          cityId: fieldsValue.companyRegisterCity[1],
          countyId: fieldsValue.companyRegisterCity[2],

          // 所在地址省市区
          locationProvinceId: fieldsValue.location[0],
          locationCityId: fieldsValue.location[1],
          locationCountyId: fieldsValue.location[2],

          // 临时字段,后端说要加，随意值
          createById: 123,
        };

        if (temId) values.id = temId;

        if (fieldsValue.dueIsForever) {
          // 营业期限是否永久
          values.dueIsForever = fieldsValue.dueIsForever ? 0 : 1;
        } else {
          values.dueIsForever = fieldsValue.dueIsForever ? 0 : 1;
          values.dueStartDate = fieldsValue.dueDate[0].format('YYYY-MM-DD');
          values.dueEndDate = fieldsValue.dueDate[1].format('YYYY-MM-DD');
        }

        // companyLogo: oss 保存图片的id
        values.companyLogo = getFileId(fieldsValue.companyLogo);

        values.businessLicenceId = getFileId(fieldsValue.businessLicenceId);

        values.temType = 1;

        dispatch({
          type: 'createCompany/saveForm',
          payload: values,
        })
          .then(id => {
            message.success('操作成功');
            history.replace(`/createCompany/company?temId=${id}`);
            if (type === 'submit') {
              history.push(`/createCompany/LegalRepresentative?temId=${id}`);
            }
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  onBlur = () => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.props;
    const companyRegisterCity = getFieldValue('companyRegisterCity'),
      companyPlaceRegister = getFieldValue('companyPlaceRegister'),
      location = getFieldValue('location'),
      companyPlace = getFieldValue('companyPlace');
    if (companyRegisterCity && companyPlaceRegister && !location && !companyPlace) {
      // 如果在填完企业注册地址的时候，经营地址两个输入框都没有值的话，复制下去给他
      setFieldsValue({
        location: companyRegisterCity,
        companyPlace: companyPlaceRegister,
      });
    }
  };
  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      companyInformation,
      loading,
      location: {
        query: { temId },
      },
      dispatch,
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const rangeConfig = {
      initialValue: companyInformation.dueStartDate
        ? [moment(companyInformation.dueStartDate), moment(companyInformation.dueEndDate)]
        : undefined,
      rules: [
        { type: 'array', required: !getFieldValue('dueIsForever'), message: '请选择证件有效期!' },
      ],
    };
    return (
      <Wrapper
        current={0}
        loading={loading}
        actions={
          <Actions
            temId={temId}
            dispatch={dispatch}
            handleSave={this.handleSubmit('save')}
            handleSubmit={this.handleSubmit('submit')}
          />
        }
      >
        <Form onSubmit={this.handleSubmit}>
          <h2>企业信息（必填）</h2>
          <Row>
            <Col span={12}>
              <FormItem {...formItemLayout} label="企业名称">
                {getFieldDecorator('name', {
                  initialValue: companyInformation.name,
                  rules: [
                    {
                      required: true,
                      message: '请输入企业名称',
                    },
                    {
                      max: 80,
                      message: '80位以内',
                    },
                  ],
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem {...formItemLayout} label="统一社会信用代码">
                {getFieldDecorator('creditCode', {
                  initialValue: companyInformation.creditCode,
                  rules: [
                    {
                      required: true,
                      message: '请输入统一社会信用代码',
                    },
                    {
                      max: 50,
                      message: '50位以内',
                    },
                  ],
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <FormItem {...formItemLayout} label="企业注册地址">
                {getFieldDecorator('companyRegisterCity', {
                  initialValue: companyInformation.cityId
                    ? [
                        companyInformation.provinceId,
                        companyInformation.cityId,
                        companyInformation.countyId,
                      ]
                    : undefined,
                  rules: [
                    {
                      required: true,
                      message: '请选择企业注册地址',
                    },
                  ],
                })(<CitySelect />)}
              </FormItem>
            </Col>
            <Col span={10}>
              <FormItem colon={false}>
                {getFieldDecorator('companyPlaceRegister', {
                  initialValue: companyInformation.companyPlaceRegister,
                  rules: [
                    {
                      required: true,
                      message: '请输入详细注册地址',
                    },
                  ],
                })(<Input onBlur={this.onBlur} />)}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem {...formItemLayout} label="企业经营地址">
                {getFieldDecorator('location', {
                  initialValue: companyInformation.locationCityId
                    ? [
                        companyInformation.locationProvinceId,
                        companyInformation.locationCityId,
                        companyInformation.locationCountyId,
                      ]
                    : undefined,
                  rules: [
                    {
                      required: true,
                      message: '请选择企业经营地址',
                    },
                  ],
                })(<CitySelect />)}
              </FormItem>
            </Col>
            <Col span={10}>
              <FormItem colon={false}>
                {getFieldDecorator('companyPlace', {
                  initialValue: companyInformation.companyPlace,
                  rules: [
                    {
                      required: true,
                      message: '请输入详细企业经营地址',
                    },
                  ],
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10}>
              <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label="营业期限">
                {getFieldDecorator('dueDate', rangeConfig)(
                  <RangePicker
                    style={{ width: '100%' }}
                    disabled={getFieldValue('dueIsForever')}
                    placeholder={['起始时间', '结束时间']}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={2}>
              <FormItem>
                {getFieldDecorator('dueIsForever', {
                  initialValue:
                    'dueIsForever' in companyInformation
                      ? companyInformation.dueIsForever === 0
                      : undefined,
                  valuePropName: 'checked',
                })(<Checkbox>长期</Checkbox>)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem {...formItemLayout} label="企业类型">
                {getFieldDecorator('companyType', {
                  initialValue: companyInformation.companyType
                    ? `${companyInformation.companyType}`
                    : undefined,
                  rules: [
                    {
                      required: true,
                      message: '请选择企业类型',
                    },
                  ],
                })(
                  <Select style={{ width: '100%' }}>
                    <Option value="1">独立公司</Option>
                    <Option value="2">法人公司</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={
                  <Tooltip
                    title={
                      <div>
                        点击
                        <a href="http://www.gsxt.gov.cn/index.htm" target="_blank">
                          企业信息公示
                        </a>
                        ，查询企业信息，复制经营范围到这里
                      </div>
                    }
                  >
                    <span>
                      企业经营范围
                      <Icon type="info-circle" style={{ marginLeft: 5 }} />
                    </span>
                  </Tooltip>
                }
              >
                {getFieldDecorator('businessScope', {
                  initialValue: companyInformation.businessScope,
                  rules: [
                    {
                      required: true,
                      message: '请输入企业经营范围',
                    },
                    {
                      max: 255,
                      message: '255位以内',
                    },
                  ],
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="营业执照证件">
                请上传彩色元件或加盖公司公章复印件 支持.png .pdf .jpg格式上传，大小5m以内.
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={3} offset={3}>
              <FormItem labelCol={{ span: 9 }} wrapperCol={{ span: 15 }}>
                {getFieldDecorator('businessLicenceId', {
                  valuePropName: 'fileList',
                  getValueFromEvent: this.normFile,
                  initialValue: companyInformation.businessLicenceId,
                  rules: [
                    {
                      required: true,
                      message: '请上传营业执照证件',
                    },
                  ],
                })(
                  <OssUpload
                    name="logo"
                    listType="picture-card"
                    data={{
                      businessId: 0,
                      businessType: 'string',
                      companyId: 0,
                      digestMethod: 1,
                      ext: '',
                      moduleCode: 'company',
                      productLineId: 0,
                      userId: 1,
                    }}
                  >
                    {getFieldValue('businessLicenceId') &&
                    getFieldValue('businessLicenceId').length === 1 ? null : (
                      <>
                        <Icon type="plus" />
                        <p>上传</p>
                      </>
                    )}
                  </OssUpload>
                )}
              </FormItem>
            </Col>
            <Col span={10}>
              <UploadImageSample />
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="企业logo">
                请上传彩色元件或加盖公司公章复印件 支持.png .pdf .jpg格式上传，大小5m以内.
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={3} offset={3}>
              <FormItem labelCol={{ span: 9 }} wrapperCol={{ span: 15 }}>
                {getFieldDecorator('companyLogo', {
                  valuePropName: 'fileList',
                  getValueFromEvent: this.normFile,
                  initialValue: companyInformation.companyLogo,
                  rules: [
                    {
                      required: true,
                      message: '请上传企业LOGO',
                    },
                  ],
                })(
                  <OssUpload
                    name="logo"
                    data={{
                      businessId: 0,
                      businessType: 'string',
                      companyId: 0,
                      digestMethod: 1,
                      ext: '',
                      moduleCode: 'company',
                      productLineId: 0,
                      userId: 1,
                    }}
                    listType="picture-card"
                  >
                    {getFieldValue('companyLogo') &&
                    getFieldValue('companyLogo').length === 1 ? null : (
                      <>
                        <Icon type="plus" />
                        <p>上传</p>
                      </>
                    )}
                  </OssUpload>
                )}
              </FormItem>
            </Col>
            <Col>
              <UploadImageSample />
            </Col>
          </Row>
        </Form>
      </Wrapper>
    );
  }
}
export default CompanyForm;
